<!-- src/view/inventory.vue -->
<template>
  <div class="inventory-container">
    <h1>库存管理</h1>

    <!-- 查询库存 -->
    <el-card class="search-card">
      <el-form :model="query" label-width="80px" inline>
        <el-form-item label="位置">
          <el-input v-model="query.location" placeholder="请输入位置" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchInventory">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 新增库存 -->
    <div class="toolbar">
      <el-button type="primary" @click="openAddDialog">新增库存</el-button>
    </div>

    <!-- 库存表格 -->
    <el-table
        :data="pagedData"
        border
        style="width: 100%"
        v-loading="loading"
        element-loading-text="数据加载中..."
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="item_id" label="物料ID" width="100" />
      <el-table-column prop="item_type" label="物料类型" width="150" />
      <el-table-column prop="quantity" label="数量" width="100" />
      <el-table-column prop="location" label="位置" width="150" />
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button
              size="small"
              type="danger"
              @click="confirmDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-if="tableData.length > 0"
        background
        layout="prev, pager, next, sizes, total"
        :current-page="page"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        :total="tableData.length"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        style="margin-top: 20px; justify-content: center;"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="editForm.id ? '编辑库存' : '新增库存'"
        width="500px"
    >
      <el-form
          :model="editForm"
          label-width="100px"
          ref="inventoryForm"
      >
        <el-form-item
            label="物料ID"
            prop="item_id"
            :rules="[{ required: true, message: '请输入物料ID', trigger: 'blur' }]"
        >
          <el-input-number
              v-model="editForm.item_id"
              :min="1"
              style="width: 100%"
              :disabled="!!editForm.id"
          />
        </el-form-item>
        <el-form-item
            label="物料类型"
            prop="item_type"
            :rules="[{ required: true, message: '请输入物料类型', trigger: 'blur' }]"
        >
          <el-input
              v-model="editForm.item_type"
              placeholder="请输入物料类型"
          />
        </el-form-item>
        <el-form-item
            label="数量"
            prop="quantity"
            :rules="[{ required: true, message: '请输入数量', trigger: 'blur' }]"
        >
          <el-input-number
              v-model="editForm.quantity"
              :min="0"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item
            label="位置"
            prop="location"
            :rules="[{ required: true, message: '请输入位置', trigger: 'blur' }]"
        >
          <el-input
              v-model="editForm.location"
              placeholder="请输入位置"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import inventoryApi from '../api/inventoryApi.js';

// 数据状态
const tableData = ref([]); // 确保初始化为空数组
const loading = ref(false);
const dialogVisible = ref(false);
const inventoryForm = ref(null);

// 分页参数
const page = ref(1);
const pageSize = ref(5);

// 计算分页数据
const pagedData = computed(() => {
  // 确保 tableData.value 是数组
  if (!Array.isArray(tableData.value)) {
    return [];
  }
  const start = (page.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value.slice(start, end);
});

// 查询条件
const query = reactive({
  item_type: '',
  location: ''
});

// 表单数据
const editForm = reactive({
  id: null,
  item_id: null,
  item_type: '',
  quantity: 0,
  location: ''
});

// 加载库存列表
const loadInventory = async () => {
  loading.value = true;
  try {
    const res = await inventoryApi.list();
    // 正确处理响应数据
    if (res && res.code === 200) {
      tableData.value = Array.isArray(res.data) ? res.data : [];
    } else {
      tableData.value = [];
      ElMessage.error(res?.msg || '数据加载失败');
    }
  } catch (err) {
    console.error('加载库存列表失败:', err);
    tableData.value = [];
    ElMessage.error('加载库存列表失败: ' + (err.message || '请检查网络连接'));
  } finally {
    loading.value = false;
  }
};

// 查询库存
const searchInventory = async () => {
  loading.value = true;
  try {
    // 构造查询参数，只包含非空值
    const params = {};
    if (query.location) params.location = query.location;
    
    const res = await inventoryApi.list(params);
    // 正确处理响应数据
    if (res && res.code === 200) {
      tableData.value = Array.isArray(res.data) ? res.data : [];
    } else {
      tableData.value = [];
      ElMessage.error(res?.msg || '查询失败');
    }
    page.value = 1;
  } catch (err) {
    console.error('查询库存失败:', err);
    tableData.value = [];
    ElMessage.error('查询库存失败: ' + (err.message || '请检查网络连接'));
  } finally {
    loading.value = false;
  }
};

// 重置查询
const resetSearch = () => {
  query.location = '';
  loadInventory();
};

// 分页事件处理
const handlePageChange = (newPage) => {
  page.value = newPage;
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  page.value = 1;
};

// 打开新增对话框
const openAddDialog = () => {
  // 重置表单
  Object.assign(editForm, {
    id: null,
    item_id: null,
    item_type: '',
    quantity: 0,
    location: ''
  });
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (inventory) => {
  Object.assign(editForm, inventory);
  dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  try {
    if (editForm.id) {
      // 编辑
      const res = await inventoryApi.edit(editForm.id, editForm);
      if (res && res.code === 200) {
        ElMessage.success('更新成功');
        dialogVisible.value = false;
        loadInventory();
      } else {
        ElMessage.error(res?.msg || '更新失败');
      }
    } else {
      // 新增
      if (!editForm.item_id || !editForm.item_type || !editForm.location) {
        ElMessage.warning('请填写完整信息');
        return;
      }

      const res = await inventoryApi.add(editForm);
      if (res && res.code === 200) {
        ElMessage.success('新增成功');
        dialogVisible.value = false;
        loadInventory();
      } else {
        ElMessage.error(res?.msg || '新增失败');
      }
    }
  } catch (err) {
    console.error('操作失败:', err);
    ElMessage.error('操作失败: ' + (err.message || '请检查网络连接'));
  }
};

// 删除库存
const confirmDelete = async (id) => {
  ElMessageBox.confirm(
      '确定要删除该库存记录吗？此操作不可恢复。',
      '删除确认',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
  ).then(async () => {
    try {
      const res = await inventoryApi.del(id);
      if (res && res.code === 200) {
        ElMessage.success('删除成功');
        loadInventory();
      } else {
        ElMessage.error(res?.msg || '删除失败');
      }
    } catch (err) {
      console.error('删除失败:', err);
      ElMessage.error('删除失败: ' + (err.message || '请检查网络连接'));
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 初始化加载数据
onMounted(() => {
  loadInventory();
});
</script>

<style scoped>
.inventory-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
  text-align: right;
}
</style>
